import { useTranslate } from '@/hooks/common-hooks';
import { CheckOutlined, CopyOutlined } from '@ant-design/icons';
import { Tooltip, message } from 'antd';
import { useRef, useState } from 'react';
import { copyTextToClipboard } from '@/utils/copy';

// 定义Props接口，与原库保持兼容
interface Props {
  text: string;
  onCopy?: (text: string, result: boolean) => void;
  options?: any;
  children?: React.ReactNode;
}

const CopyToClipboard = ({ text, onCopy }: Props) => {
  const [copied, setCopied] = useState(false);
  const { t } = useTranslate('common');
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const handleCopy = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (timeoutRef.current) clearTimeout(timeoutRef.current);

    const result = await copyTextToClipboard(text);
    setCopied(result);
    onCopy?.(text, result);

    if (result) {
      timeoutRef.current = setTimeout(() => setCopied(false), 2000);
    } else {
      message.error(t('copy_failed'));
    }
  };

  return (
    <Tooltip title={copied ? t('copied') : t('copy')}>
      <span onClick={handleCopy} style={{ cursor: 'pointer' }}>
        {copied ? <CheckOutlined /> : <CopyOutlined />}
      </span>
    </Tooltip>
  );
};

export default CopyToClipboard;
